package demoMod.anm2editor.ui;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import demoMod.anm2editor.fonts.FontKeys;
import demoMod.anm2editor.localization.LocalizedStrings;
import demoMod.anm2editor.model.Operation;
import demoMod.anm2editor.model.Project;
import demoMod.anm2editor.model.SpriteSheet;
import demoMod.anm2editor.utils.IdGenerator;
import demoMod.gdxform.core.AbstractAction;
import demoMod.gdxform.core.FormManager;
import demoMod.gdxform.helpers.FontHelper;
import demoMod.gdxform.ui.*;

import java.io.File;
import java.util.List;

public class SpriteSheetList extends GList<SpriteSheetItem> {
    @Override
    public void update() {
        for (ListCellRenderer<SpriteSheetItem> listCellRenderer : getElements()) {
            listCellRenderer.setWidth(getWidth());
        }
        super.update();
    }

    @Override
    public float getWidth() {
        return getParent() == null ? Gdx.graphics.getWidth() : getParent().getWidth();
    }

    @Override
    public boolean clickDown(int screenX, int screenY, int button) {
        if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT)) return false;
        if (super.clickDown(screenX, screenY, button)) {
            return true;
        }
        RegionManager regionManager = (RegionManager) FormManager.getInstance().getContainerById(RegionManager.ID);
        if (screenX > regionManager.getX(true) && screenX < regionManager.getX(true) + getWidth() && Gdx.graphics.getHeight() - screenY > regionManager.getY(true)
                && Gdx.graphics.getHeight() - screenY < regionManager.getY(true) + regionManager.getHeight() - regionManager.getBannerHeight() && button == Input.Buttons.RIGHT) {
            GMenuList menuList = new GMenuList();
            menuList.setWidth(150.0F);
            menuList.setX(screenX);
            menuList.setY(Gdx.graphics.getHeight() - screenY);

            List<String> strings = LocalizedStrings.getStrings(RegionManager.ID);
            List<String> fileSelectWindowStrings = LocalizedStrings.getStrings("FileSelectWindow");
            GMenuItem newSprite = new GMenuItem(menuList.getWidth(), menuList.getMenuItemHeight(), strings.get(1) + "...", FontHelper.getFont(FontKeys.SIM_HEI_14)) {
                @Override
                public void onClick() {
                    GFileSelectWindow fileSelectWindow = new GFileSelectWindow(FontHelper.getFont(FontKeys.SIM_HEI_14));
                    fileSelectWindow.setTitle(strings.get(2));
                    fileSelectWindow.setConfirmText(fileSelectWindowStrings.get(0));
                    fileSelectWindow.setCancelText(fileSelectWindowStrings.get(1));
                    fileSelectWindow.setBackText(fileSelectWindowStrings.get(2));
                    fileSelectWindow.setFileFilter(file -> file.isDirectory() || file.getName().endsWith(".png") || file.getName().endsWith(".PNG"));
                    fileSelectWindow.setPath(Project.currentProject.getFilePath());
                    fileSelectWindow.setConfirmCallback((path, selectedFiles) -> {
                        if (!selectedFiles.isEmpty()) {
                            String filepath = selectedFiles.get(0).getAbsolutePath();
                            Texture region = new Texture(Gdx.files.absolute(filepath));
                            SpriteSheet spriteSheet = new SpriteSheet();
                            spriteSheet.setSprite(region);
                            spriteSheet.setPath(filepath.replace(Project.currentProject.getFilePath() + File.separator, ""));
                            spriteSheet.loadAtlasData();
                            int id = IdGenerator.nextSpriteSheetId();
                            Project.currentProject.addSpriteSheet(id, spriteSheet);
                            SpriteSheetItem item = new SpriteSheetItem(FontHelper.getFont(FontKeys.SIM_HEI_14));
                            item.setSpriteSheet(spriteSheet);
                            item.setId(Integer.toString(id));
                            addItem(item);

                            GScrollPane scrollPane = ((RegionManager) FormManager.getInstance().getContainerById(RegionManager.ID)).getScrollPane();
                            if (getElements().size() * getCellHeight() > scrollPane.getPlainHeight()) {
                                scrollPane.setPlainHeight(scrollPane.getPlainHeight() + getCellHeight());
                            }
                            Operation operation = new Operation() {
                                @Override
                                public void undo() {
                                    IdGenerator.setSpriteSheetId(id);
                                    Project.currentProject.removeSpriteSheet(id);
                                    removeItem(item);
                                    actionManager.addToSequenceBot(new AbstractAction.Builder().setActionBody(duration -> {
                                        if (Project.currentProject.getSpriteSheets().size() * getCellHeight() < scrollPane.getPlainHeight()
                                                && scrollPane.getPlainHeight() - getCellHeight() > scrollPane.getHeight()) {
                                            scrollPane.setPlainHeight(scrollPane.getPlainHeight() - getCellHeight());
                                        }
                                        return true;
                                    }).build());
                                    spriteSheet.dispose();
                                }

                                @Override
                                public void redo() {
                                    IdGenerator.setSpriteSheetId(id + 1);
                                    Texture region = new Texture(Gdx.files.absolute(filepath));
                                    spriteSheet.setSprite(region);
                                    Project.currentProject.addSpriteSheet(id, spriteSheet);
                                    addItem(item);
                                    if (getElements().size() * getCellHeight() > scrollPane.getPlainHeight()) {
                                        scrollPane.setPlainHeight(scrollPane.getPlainHeight() + getCellHeight());
                                    }
                                }
                            };
                            operation.setName(strings.get(3));
                            ((HistoryPanel) FormManager.getInstance().getContainerById(HistoryPanel.ID)).addOperation(operation);
                        }
                    });
                }
            };
            if (Project.currentProject.getFilePath() == null) {
                newSprite.setEnabled(false);
            }
            newSprite.setSplitLine(false);
            menuList.addElement(newSprite);
            FormManager.getInstance().addContainer(menuList);
            FormManager.getInstance().moveToTop(menuList);
            return true;
        }
        return false;
    }
}
